package com.biqee.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.io.IOUtils;

import com.biqee.constant.SystemConstant;

public class StoreUtil {
	public static final String  STORE_ROOT=  EnvUtil.getFileStore();

	
	/**
	 * 存储文件
	 * @param path
	 * @param content
	 * @param encoding
	 * @throws IOException
	 */
	public static String storeFile(String storeFoler, String content,String encoding) throws IOException{
		String path = STORE_ROOT+storeFoler ;
		File file = new File(path);
		createParentIfNotExist(file);
		OutputStream out = new FileOutputStream(file);
		IOUtils.write(content,out ,encoding);
		IOCloseUtil.safeClose(out);
		return path ;
	}
	

	
	
	/**
	 * 存储文件
	 * @param path
	 * @param content
	 * @param encoding
	 * @throws IOException
	 */
	public static String storeFile(String storeFoler, InputStream in,String encoding) throws IOException{
		String str  = IOUtils.toString(in,encoding);
		return storeFile(storeFoler,str,encoding);
	}
	
	public static String readFile(String relativePath,String encoding) throws IOException{
		InputStream in = new FileInputStream(STORE_ROOT+relativePath);
		String path = IOUtils.toString(in,encoding);
		IOCloseUtil.safeClose(in);
		return path ;
	}
	
	/**
	 * 按日期创建文件夹,并根据lastFolder 建立子目录
	 * @param lastFolder
	 * @param prifix
	 */
	public static String  createRelativeFilePath(String fileName){
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		int date = cal.get(Calendar.DATE);
		return SystemConstant.FILE_SEPARATOR+year+month+date+SystemConstant.FILE_SEPARATOR+fileName ;
	}
	
	
	private static void createParentIfNotExist(File file) throws IOException{
		if(!file.exists()){
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
		}
	}
	


}
